from random import randint

from django.http import HttpResponse, JsonResponse

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.views import APIView
from utils.captcha.captcha import captcha


class ImageCodeView(APIView):

    def get(self, request, uuid):
        # 步骤
        # 1 获取uuid
        print(uuid)
        # 2 生成图片验证码 和二进制图片数据
        text, image = captcha.generate_captcha()
        print(text)
        # 3 redis保存验证码 用uuid为key 有效期
        redis_cli = get_redis_connection("captcha")
        # uuid为key  120s是过期时间
        redis_cli.setex(uuid, 120, text)
        # 4 返回二进制图片数据

        return HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(APIView):
    """短信验证码"""
    def get(self, request, mobile):
        print(mobile)
        # 1 生成验证码
        sms_code = "%04d" % randint(0, 9999)
        print(sms_code)
        # 2 创建redis连接对象
        redis_conn = get_redis_connection('captcha')
        # 3 把验证码存储到redis的数据库
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # 4 返回响应
        return JsonResponse({'code': '0', 'errmsg': 'ok'})